<?php 
class CAttr extends Zend_Db_Table
{
	protected $_name;
	protected $_primary;
	public function __construct()
	{
		$this->_name=R_PRE. "attr";
		$this->_primary = 'attr_id';
		parent::__construct();
	}
	
	public function add($data)
	{
		return $this->insert($data);
	}

	public function updateAttr($attrName, $attrOrder, $attrId, $attrDesc, $type = 0)
	{
		if ($attrId) {
			$productAttr = new CProductattr();
			$productAttr->update(array('attr_value'=>$attrName), 'attr_id_ex = ' . intval($attrId));
			return $this->update(array('attr_name'=>$attrName, 'attr_order'=>$attrOrder, 'attr_desc'=>$attrDesc), 'attr_id = ' . intval($attrId));
		} else {
			return $this->add(array('attr_name'=>$attrName, 'attr_order'=>$attrOrder, 'type'=>$type));
		}
	}
	
	public function exist($name, $type)
	{
		return $this->fetchRow(array('attr_name = ?'=>$name, 'type = ?'=>$type));
	}
	
	public function getByType($type)
	{
		return $this->fetchAll(array('type = ?'=>$type), 'attr_order asc');
	}
	
	public function del($id)
	{
		$productAttr = new CProductattr();
		$row = $productAttr->fetchRow(array('attr_id_ex = ?'=>$id));
		if ($row) {
			return 1;
		}
		if ($this->delete('attr_id = ' . intval($id))) {
			return 0;
		}
	}
	
	public function checkProduct($where, $filter = array())
	{
		$itemShow=new CItemShow();
		$itemShow->setType('product');
        $itemShow->setWhere($where);
        $itemCounts=$itemShow->getAllItemCounts($filter);
        return $itemCounts;
	}
	
	public function filterItemIdByAttr($itemIds, $attrId, $isCount = 0)
	{
		$productAttr = new CProductattr();
		$rows = $productAttr->fetchAll(array('attr_id_ex = ?'=>$attrId));
		$return = array();
		if (count($rows) > 0) {
			$tmp = array();
			foreach ($rows as $v) {
				$tmp[] = $v->itemid;
			}
			foreach ($itemIds as $v) {
				if (in_array($v, $tmp)) {
					$return[] = $v;
				}
			}
		}
		if ($isCount) {
			return count($return);
		}
		return $return;
	}
}